package com.crawler.dao;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.jupiter.api.Test;


public class TestDao {

	@Test
	public void test() {
		long startTime = System.currentTimeMillis();
		int count = 100000;
		int pools = 64;
		CountDownLatch latch = new CountDownLatch(count);
		ExecutorService executorService = Executors.newFixedThreadPool(pools);
		for (int i = 0; i < count; i++) {
			Handler hand = new Handler();
			hand.setLatch(latch);
			hand.setName("测试名称"+i);
			hand.setAuthor("测试作者"+i);
			executorService.execute(hand);
		}
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			executorService.shutdown();
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总耗时:"+(new BigDecimal(endTime-startTime)).divide(new BigDecimal(1000L))+"秒");
	}
	
	public static void save(String name ,String author){
		Connection connect = null;
		try {
//			connect = DruidUtil.getDataSource().getConnection();
//			connect = DruidDrive.getInstence().getConnection();
			connect = C3P0Drive.getInstence().getConnection();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			QueryRunner qr=new QueryRunner();
			ResultSetHandler<Integer> res = new MyResultSetHandler();
			String sql = "INSERT INTO books(name, author,date) VALUES(?,?,?)";
			Object params[] = {name,author, new Date()};
			qr.insert(connect, sql, new ScalarHandler<>(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				connect.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}			
	}
}
class Handler implements Runnable{
	private CountDownLatch latch;
	private String name;
	private String author;
	@Override
	public void run() {
		TestDao.save(name, author);
		latch.countDown();
	}
	
	public CountDownLatch getLatch() {
		return latch;
	}
	public void setLatch(CountDownLatch latch) {
		this.latch = latch;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
}

